package com.jeeplus.cms.util;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ShearCaptcha;
import cn.hutool.crypto.SecureUtil;
import com.jeeplus.modules.cms.guestbook.vo.CaptchaVo;
import org.apache.commons.lang3.StringUtils;

import java.awt.*;

/**
 * 验证码工具类
 *
 * @author WuXilin
 */
public class CaptchaUtils {

    public static CaptchaVo getCaptcha() {
        // 生成扭曲干扰验证码
        ShearCaptcha shearCaptcha = CaptchaUtil.createShearCaptcha(250, 95, 4, 4);
        shearCaptcha.setFont(new Font(Font.MONOSPACED, Font.BOLD, 60));

        // 构建缓存key,用于存储对应的验证码
        String code = shearCaptcha.getCode();
        String key = SecureUtil.md5(code + System.currentTimeMillis());
        String lowerCaseCode = code.toLowerCase();

        // 换入缓存中
        String realKey = SecureUtil.md5(lowerCaseCode + key);
        CmsCacheUtils.putCaptcha(realKey, lowerCaseCode);

        // 验证码Vo对象
        CaptchaVo captcha = new CaptchaVo();
        captcha.setKey(key);
        captcha.setCaptcha("data:image/png;base64," + shearCaptcha.getImageBase64());

        return captcha;
    }

    public static boolean validateCaptcha(CaptchaVo captchaVo) {
        String key = captchaVo.getKey();
        String captcha = captchaVo.getCaptcha();
        if (StringUtils.isBlank(key) || StringUtils.isBlank(captcha)) {
            return false;
        }

        // 构建验证码缓存key，获取缓存中的验证码
        captcha = captcha.toLowerCase();
        String realKey = SecureUtil.md5(captcha + key);
        Object checkCode = CmsCacheUtils.getCaptcha(realKey);
        return checkCode != null && checkCode.equals(captcha);
    }
}
